package org.jivesoftware.spark;

import org.jivesoftware.resource.SoundsRes;
import org.jivesoftware.spark.util.TaskEngine;
import org.jivesoftware.spark.util.log.Log;

import java.applet.Applet;
import java.applet.AudioClip;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class SoundManager
{
	private final Map<String, AudioClip> clipMap = new HashMap<String, AudioClip>();
	private final Map<URL, AudioClip> fileMap = new HashMap<URL, AudioClip>();
	
	public SoundManager()
	{
	}
	
	public AudioClip getClip(String clip)
	{
		if (!clipMap.containsKey(clip))
		{
			final AudioClip newClip = loadClipForURL(clip);
			if (newClip != null)
			{
				clipMap.put(clip, newClip);
			}
		}
		
		return clipMap.get(clip);
	}
	
	public void playClip(final AudioClip clip)
	{
		final Runnable playThread = new Runnable()
		{
			public void run()
			{
				try
				{
					clip.play();
				}
				catch(Exception ex)
				{
					System.err.println("Unable to load sound file");
				}
			}
		};
		
		TaskEngine.getInstance().submit(playThread);
	}
	
	public void playClip(String clipToPlay)
	{
		AudioClip clip = getClip(clipToPlay);
		try
		{
			clip.play();
		}
		catch(Exception ex)
		{
			System.err.println("Unable to load sound file");
		}
	}
	
	public void playClip(final File soundFile)
	{
		final Runnable playThread = new Runnable()
		{
			public void run()
			{
				try
				{
					final URL url = soundFile.toURI().toURL();
					AudioClip ac = fileMap.get(url);
					if (ac == null)
					{
						ac = Applet.newAudioClip(url);
						fileMap.put(url, ac);
					}
					ac.play();
				}
				catch(MalformedURLException e)
				{
					Log.error(e);
				}
			}
		};
		
		TaskEngine.getInstance().submit(playThread);
	}
	
	private AudioClip loadClipForURL(String clipOfURL)
	{
		final URL url = SoundsRes.getURL(clipOfURL);
		AudioClip clip = null;
		
		try
		{
			clip = Applet.newAudioClip(null);
		}
		catch(Exception e)
		{
			Log.error("Unable to load sound url: " + url + "\n\t: " + e);
		}
		
		return clip;
	}
}
